/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.alibaba.dubbo.admin.web.mvc.home;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.dubbo.admin.governance.service.ProviderService;
import com.alibaba.dubbo.admin.registry.common.domain.ProviderPO;

import org.springframework.beans.factory.annotation.Autowired;

public class UnregisterallController extends AbstractShellController {

    @Autowired
    private ProviderService providerService;

    @Autowired
    private HttpServletRequest request;

    @Override
    protected String doExecute(Map<String, Object> context) throws Exception {
        String address = request.getParameter("provider");
        if (address == null || address.length() == 0) {
            address = request.getParameter("client");
        }
        if (address == null || address.length() == 0) {
            throw new IllegalArgumentException("The url provider parameter is null! Usage: " + request.getRequestURL().toString() + "?provider=" + operatorAddress);
        }
        List<ProviderPO> providerPOS = providerService.findByAddress(address);
        if (providerPOS != null && providerPOS.size() > 0) {
            for (ProviderPO providerPO : providerPOS) {
                if (!currentUserPO.hasServicePrivilege(providerPO.getService())) {
                    throw new IllegalStateException("The user " + currentUserPO + " have no privilege of service " + providerPO.getService());
                }
            }
            for (ProviderPO providerPO : providerPOS) {
                providerPO.setUsername(operator);
                providerPO.setOperatorAddress(operatorAddress);
                providerService.deleteStaticProvider(providerPO.getId());
            }
        }
        return "UnregisterController " + (providerPOS == null ? 0 : providerPOS.size()) + " services.";
    }

}
